<template>
  <div class="main">
    <el-row :gutter="20">
      <el-col :span="4">
        <p class="label-form"> 用户手机号：</p>
        <el-input v-model="queryParams.phone"  placeholder="请输入品牌名称"></el-input>
      </el-col>
<!--      <el-col :span="4">-->
<!--        <p class="label-form"> 状态：</p>-->
<!--        <el-select style="width: 100%;" clearable v-model="queryParams.status" placeholder="请选择">-->
<!--          <el-option-->
<!--            v-for="item in messageType"-->
<!--            :key="item.dictValue"-->
<!--            :label="item.dictLabel"-->
<!--            :value="Number(item.dictValue)">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-col>-->
<!--      <el-col :span="4">-->
<!--        <p class="label-form"> 申请类型：</p>-->
<!--        <el-select style="width: 100%;" clearable v-model="queryParams.type" placeholder="请选择">-->
<!--          <el-option-->
<!--            v-for="item in optionsType"-->
<!--            :key="item.dictValue"-->
<!--            :label="item.dictLabel"-->
<!--            :value="Number(item.dictValue)">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-col>-->
      <el-col :span="6">
        <p class="label-form"></p>
        <el-button type="primary" @click="getSelect"  icon="el-icon-search">搜索</el-button>
        <el-button type="warning" @click="resert" icon="el-icon-refresh-right">重置</el-button>
      </el-col>
    </el-row>

    <!--    <el-row :gutter="20" style="margin-top: 10px">-->
    <!--      <el-col :span="4">-->
    <!--        <el-button @click="addShop" type="primary" icon="el-icon-plus">新增</el-button>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <el-table :data="tableData" max-height="500" border style="margin-top: 30px">
      <el-table-column align="center" prop="id" min-width="100" label="ID"></el-table-column>
      <el-table-column prop="orderSn" min-width="200" label="订单号"></el-table-column>
      <el-table-column prop="carModel" min-width="200" label="车辆信息"></el-table-column>
      <el-table-column prop="licensePlate" min-width="200" label="车牌号"></el-table-column>
      <el-table-column prop="userPhone" min-width="200" label="手机号"></el-table-column>
      <el-table-column prop="ext" width="100"  label="救援位置 ">
        <template slot-scope="scope">

          <el-button icon="el-icon-view" @click="viewShop(scope.row)" type="primary" size="mini">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="img" min-width="200"  label="车辆照片">
        <template slot-scope="scope">
          <el-image style="height: 40px" :src="scope.row.carImg"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="storeName" width="200"  label="店铺名称 "></el-table-column>
      <el-table-column prop="storeAddress" width="200"  label="店铺地址 "></el-table-column>
      <el-table-column prop="ext" width="200"  label="救援类型 "></el-table-column>

      <el-table-column prop="status" width="200"  label="救援状态 ">
        <template slot-scope="scope">
          {{ status(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column min-width="180"  prop="status" label="创建时间">
        <template slot-scope="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="250" align="center" label="操作">
        <template slot-scope="scope">
                    <el-button type="danger"
                               v-if="scope.row.type !== 3 && scope.row.status ===1"
                               size="mini"
                               icon="el-icon-s-finance"
                               @click="uploadRescueImages(scope.row)">救援处理</el-button>
                    <el-button type="primary"
                               v-if="scope.row.type !== 3 && scope.row.status ===2"
                               size="mini"
                               icon="el-icon-view"
                               @click="viewImage(scope.row)">查看图片</el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="救援位置"
      :visible.sync="dialogVisible"
      width="900px"
      :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="">
          <baidu-map
            class="map"
            @click="setMark"
            style="display: flex; flex-direction: column"
            :center="center"
            :zoom="15"
            :scroll-wheel-zoom="true">
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
            <bm-marker
              :position="mark"
              :dragging="true" animation="BMAP_ANIMATION_BOUNCE">
              <bm-label
                :content="content"
                :labelStyle="{color: 'red', fontSize : '12px'}"
                :offset="{width: -35, height: 30}"/>
            </bm-marker>
            <bm-driving
              :start="center"
              :end="mark"
              :auto-viewport="true"
              policy="BMAP_DRIVING_POLICY_LEAST_DISTANCE"
              :panel="false"
              :location="mark"
            >
            </bm-driving>

          </baidu-map>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="耗材管理"
      :visible.sync="isConsumables"
      width="900px"
      :before-close="handConsumables">
      <el-button icon="el-icon-plus" @click="addTable" type="primary" style="margin: 10px 0">添加</el-button>
      <el-table :data="materialScienceList" border style="width: 100%">
        <el-table-column prop="name" label="材料名称" min-width="180">
          <template slot-scope="scope">
            <el-select style="width: 100%;"
                       clearable
                       :disabled="scope.row.isChecked"
                       filterable
                       @change="changeProduct(scope.row,scope.row.equipmentId)"
                       v-model="scope.row.equipmentId"
                       placeholder="请选择">
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name+'_' + item.model"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量" min-width="180">
          <template slot-scope="scope">
              <el-input v-if="!scope.row.isChecked" placeholder="请输入数量" type="number" v-model="scope.row.num"></el-input>
            <span v-else>{{scope.row.num}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" min-width="180">
          <template slot-scope="scope">
            {{Number(scope.row.num)*Number(scope.row.price)}}
          </template>
        </el-table-column>
        <el-table-column prop="price" align="center" label="操作" min-width="130">
          <template slot-scope="scope">
            <el-button size="mini" v-if="!scope.row.isChecked" @click="submitNum(scope.row)" type="primary">确定</el-button>
            <el-button size="mini" v-if="scope.row.isChecked" @click="updateForm(scope.row)" type="warning">修改</el-button>
            <el-button size="mini" @click="deleteForm(scope.row)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handConsumables">关闭</el-button>
        <el-button type="primary" v-if="!isProEdit" @click="insertForm">添加耗材</el-button>
        <el-button type="primary" v-else @click="updateFormConsumables">修改耗材</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="结算"
      :visible.sync="payStatus"
      width="900px"
      :before-close="handleClosePayStatus">
      <el-table
        :data="materialScienceList"
        border
        style="width: 100%">
        <el-table-column prop="name" label="材料名称" min-width="180">

        </el-table-column>
        <el-table-column prop="num" label="数量" min-width="180">

        </el-table-column>
        <el-table-column prop="price" label="价格" min-width="180">

        </el-table-column>

      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateOrder">结算</el-button>
        <el-button type="primary" @click="payStatus = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="救援处理"
      :visible.sync="isUploadImages"
      width="900px"
      :before-close="handleCloseImage">
      <el-form ref="form" :model="uploadForm" v-if="isUpload" label-width="110px">
        <el-form-item label="车辆正面照片">
          <lz-upload :img-src="uploadForm.positive" @uploadImage="uploadImage"></lz-upload>
        </el-form-item>
        <el-form-item label="车辆左侧照片">
          <lz-upload :img-src="uploadForm.leftSide" @uploadImage="uploadImage1"></lz-upload>
        </el-form-item>
        <el-form-item label="车辆右侧照片">
          <lz-upload :img-src="uploadForm.rightSide" @uploadImage="uploadImage2"></lz-upload>
        </el-form-item>
        <el-form-item label="车辆后面照片">
          <lz-upload :img-src="uploadForm.behind" @uploadImage="uploadImage3"></lz-upload>
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="uploadForm" v-else label-width="110px">
        <el-form-item label="车辆正面照片">
          <el-image :src="uploadForm.positive" style="height: 100px"></el-image>

        </el-form-item>
        <el-form-item label="车辆左侧照片">
          <el-image :src="uploadForm.leftSide" style="height: 100px"></el-image>

        </el-form-item>
        <el-form-item label="车辆右侧照片">
          <el-image :src="uploadForm.rightSide" style="height: 100px"></el-image>

        </el-form-item>
        <el-form-item label="车辆后面照片">
          <el-image :src="uploadForm.behind" style="height: 100px"></el-image>

        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isUpload" @click="helpStatus">立即处理</el-button>
        <el-button type="primary" @click="handleCloseImage">关闭</el-button>
      </span>
    </el-dialog>
    <div class="box-pager">
      <pagination
        v-show="pager.total>0"
        :total="pager.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getListsPage"
      />
    </div>
    <div class="safe"></div>


  </div>
</template>

<script>
import {parseTime} from "@/utils/ruoyi";
import axios from "axios";
import {
  applicationList,
  equipmentInsert, equipmentUpdate, equipmentUseLogList3,
  getDict,
  getEquipment,
  getOrders,
  getProList,
  getRequestArray, orderFinish, updateApplicationStatus,
  updateRequestStatus,
  userTyreList
} from "@/api/apiFox";

export default {
  data() {
    return {
      currentPage1: 1,
      value1: '',
      pager: {
        total:10
      },
      formData:{},
      form: {},
      center: {lng: 117.404, lat: 35.915},
      productForm:{},
      dialogVisible: false,
      isEdit: false,
      isUploadImages:false,
      isProEdit:false,
      payStatus:false,
      isConsumables:false,
      isUpload:false,
      dialogVisibleTyre:false,
      mark: {lng: '', lat: ''},
      content:"",
      materialScienceList:[
        {id:1,equipmentId:"",num:"",price:"",total:"",type:0,isChecked:false}
      ],
      tyreList:[],
      tableData: [],
      queryParams:{
        pageNum:1,
        pageSize:10,
        status:1,
      },
      loading:false,
      messageType:[],
      expandedRowKeys:[],
      //adminImg：URL1+，+
      options: [
        {value: 0, label: '待审核'},
        {value: 1, label: '已审核'},
        {value: 2, label: '已完成'},
        {value: 3, label: '已驳回'},
      ],
      postions:[
        {value: 1, label: '左前'},
        {value: 2, label: '右前'},
        {value: 3, label: '左后'},
        {value: 4, label: '右后'},
      ],
      optionsType:[],
      productList:[],
      uploadForm:{
        id:"",
        positive:"",
        leftSide:"",
        rightSide:"",
        behind:"",
      }
    }
  },
  created() {
    this.getDictList('apply_status')
    this.getProductArray()
    this.getDictList2('extension_request_type')
  },
  mounted() {
    this.getLists(this.queryParams)
  },
  methods: {

    handleCloseImage(){
      this.isUploadImages = false
      this.uploadForm.image = ""
      for(let key in this.uploadForm){
        this.uploadForm[key] = ""
      }
    },

    uploadImage(e){
      this.uploadForm.positive = e
    },
    uploadImage1(e){
      this.uploadForm.leftSide = e
    },
    uploadImage2(e){
      this.uploadForm.rightSide = e
    },
    uploadImage3(e){
      this.uploadForm.behind = e
    },

    helpStatus(){
      if (!this.uploadForm.positive){
        this.$message.error('正面照未上传')
        return
      }
      if (!this.uploadForm.leftSide){
        this.$message.error('左侧照未上传')
        return
      }
      if (!this.uploadForm.rightSide){
        this.$message.error('右侧照未上传')
        return
      }
      if (!this.uploadForm.behind){
        this.$message.error('后侧照未上传')
        return
      }
      let s = [this.uploadForm.positive,this.uploadForm.leftSide,this.uploadForm.rightSide,this.uploadForm.behind]
      updateApplicationStatus(
        {
          id:this.uploadForm.id,
          status:2,
          adminImg:s.toString()
        }).then(res=>{
        this.$message.success('已处理')
        this.handleCloseImage()
        this.getLists(this.queryParams)
      })
      console.log(this.uploadForm)
    },
    getProductArray(){
      getProList().then(res=>{
        console.log(res)
        this.productList = res
      })
    },
    getDictList(item){
      getDict(item).then(res=>{
        console.log(res)
        this.messageType = res
      })
    },
    getDictList2(item){
      getDict(item).then(res=>{
        this.optionsType = res
      })
    },
    getListsPage(e){
      this.queryParams.pageNum = e.page
      this.queryParams.pageSize = e.limit
      this.getLists(this.queryParams)
    },
    resert(){
      this.queryParams={
        pageNum:1,
        pageSize:10,
        phone:"",
        status:"",
        type:""
      }
      this.getLists(this.queryParams)
    },
    getSelect(){
      this.getLists(this.queryParams)
    },
    changeProduct(value,e){

      if (this.productList && this.productList.length>0){
        let s = this.productList.filter(value => {return value.id === e})
        this.materialScienceList.forEach(value1=>{
          if (value1.id === value.id){
            value1.equipmentId = s[0].id
            value1.total = s[0].num
            value1.num = 1
            value1.price = value1.num*s[0].price
          }
        })
      }
    },

    submitNum(row){
      console.log(row)
      this.materialScienceList.forEach(value1=>{
        if (value1.id === row.id){
          if (value1.total>0){
            value1.total -= Number(row.num)
            value1.isChecked=true
          }else{
            this.$message.error('库存不足，请添加库存')
          }

        }
      })

    },

    updateForm(row){
      this.materialScienceList.forEach(value1=>{
        if (value1.id === row.id){
          value1.isChecked=false
        }
      })
    },

    deleteForm(row){
      this.materialScienceList = this.materialScienceList.filter(value => {return value.id !==row.id})
    },

    handConsumables(){
      this.materialScienceList = []
      this.isConsumables = false
      this.getLists(this.queryParams)
    },

    parseTime,
    getLists(params) {
      applicationList(params).then(res=>{
        console.log(res)
        this.pager.total=res.total
        this.tableData =res.rows
      })
    },

    handleExpand(row,expandedRows) {
      this.loading=true
      const currentRowId = row.id;
      this.tyreForm = row
      const index = this.expandedRowKeys.indexOf(currentRowId);
      if (index === -1) {

        this.expandedRowKeys = [currentRowId];
      } else {
        this.expandedRowKeys = [];
      }
      console.log(row)
      this.getTyre(row.carId)
    },
    // 上传救援图片
    uploadRescueImages(row){
      this.uploadForm.id = row.id
      this.isUploadImages = true
      this.isUpload=true
    },

    viewImage(row){
      this.isUpload=false
      if(row.adminImg){
        let form = row.adminImg.split(',')
        if (form && form.length>3){
          this.uploadForm = {
            id:row.id,
            positive:form[0],
            leftSide:form[1],
            rightSide:form[2],
            behind:form[3],
          }
        }else{
          this.$message.error('图片未上传')
        }

        this.isUploadImages = true
      }else{
        this.$message.error('图片未上传')
      }

    },

    getTyre(item){
      userTyreList({carId:item}).then(res=>{
        console.log(res)
        this.tyreList = res.data
        this.loading=false
      })
    },


    addTable(){
        let length = this.materialScienceList.length
        this.materialScienceList.unshift(
          {id:length+1,equipmentId:"",num:"",price:"",total:"",type:0,isChecked:false}
        )
    },

    insertForm(){
      console.log()
      let array = []
      this.materialScienceList.forEach(value=>{
        array.push({equipmentId: value.equipmentId, type: 0, num: value.num, requestId: this.productForm.id})
      })
      console.log(array)
      equipmentInsert(array).then(res=>{
        this.$message.success('添加成功')
        this.handConsumables()
      })
    },

    updateFormConsumables(){
      let array = []
      this.materialScienceList.forEach(value=>{
        array.push({equipmentId: value.equipmentId, type: 0, num: value.num, requestId: this.productForm.id})
      })
      equipmentUpdate(array).then(res=>{
        this.$message.success('修改成功')
        this.handConsumables()
      })
    },

    addType(e){
      this.formData={}
      this.dialogVisibleTyre = true
    },

    viewReject(row){
      this.$alert(row.reply, '驳回理由', {
        confirmButtonText: '关闭',
        callback: action => {

        }
      });

    },


    settlement(row){
      this.payStatus = true
      this.productForm=row
      equipmentUseLogList3({requestId:row.id}).then(res=>{
        console.log(res)
        let array =[]
        // {id:length+1,equipmentId:"",num:"",price:"",total:"",type:0,isChecked:false}
        if(res && res.length>0){
          res.forEach(value=>{
            this.productList.forEach(value1=>{
              if (value.requestId === value1.id){
                array.push({
                  id:value.id,
                  equipmentId:value.requestId,
                  name:value.model,
                  num:value.num,
                  price:value1.price,
                  total:value1.num,
                  type:0,
                  isChecked:true})
              }
            })
          })
          this.isProEdit=true
          this.materialScienceList = array
        }else{
          this.isProEdit=false
          this.materialScienceList = []
        }
      })

    },

    updateOrder(){
      console.log(this.productForm)
      orderFinish({id:this.productForm.id}).then(res=>{
        this.$message.success('订单已完成')
        this.getLists(this.queryParams)
      })
    },

    addConsumables(row){
      this.isConsumables = true
      this.productForm=row
      equipmentUseLogList3({requestId:row.id}).then(res=>{
        console.log(res)
        let array =[]
        // {id:length+1,equipmentId:"",num:"",price:"",total:"",type:0,isChecked:false}
        if(res && res.length>0){
          res.forEach(value=>{
            this.productList.forEach(value1=>{
              if (value.requestId === value1.id){
                array.push({
                  id:value.id,
                  equipmentId:value.requestId,
                  num:value.num,
                  price:value1.price,
                  total:value1.num,
                  type:0,
                  isChecked:false
                })
              }
            })
          })
          this.materialScienceList = array
        }else{
          this.isProEdit=false
          this.materialScienceList = []
        }
      })
    },

    handleCloseTyre(){
      this.dialogVisibleTyre =false
    },
    handleClosePayStatus(){
      this.payStatus = false
    },
    setMark(e) {
      console.log(e)
      this.center= {lng: e.point.lng, lat: e.point.lat}
    },
    updateShop(item) {
      this.dialogVisible = true
      this.form = item
      this.mark = {lng: item.longitude, lat: item.latitude}
      this.center = {lng: item.longitude, lat: item.latitude}
      this.isEdit = true
    },
    viewShop(item) {
      this.dialogVisible = true
      this.form = item
      this.content = item.storeName || '暂无数据'
      this.mark = {lng: item.longitude, lat: item.latitude}
      this.center = {lng: item.longitude, lat: item.latitude}
      this.isEdit = false
    },
    addShop() {
      this.dialogVisible = true
      this.form = {}
      this.isEdit = false
    },
    deleteTyre(item){
      console.log(item)
    },
    position(val) {
      switch (val) {
        case 1: {
          return '左前'
        }
        case 2: {
          return '右前'
        }
        case 3: {
          return '左后'
        }
        case 4: {
          return '右后'
        }
      }
    },

    handleClose() {
      this.dialogVisible = false
    },
    status(val) {
      switch (val) {
        case 0: {
          return '待审核'
        }
        case 1: {
          return '已审核'
        }
        case 2: {
          return '已完成'
        }
        case 3: {
          return '已驳回'
        }

      }
    },
    requestType(val) {
      let s = this.optionsType.filter(value => {return Number(value.dictValue) === val})
      if (s && s.length>0){
        return s[0].dictLabel
      }else{
        return  '暂无数据'
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    }
  },
}
</script>


<style scoped lang="scss">
.map {
  width: 100%;
  height: 500px;
}

.main {
  width: 100%;
  min-height: 100vh;
  padding: 30px;
  box-sizing: border-box;

  .label {
    font-size: 14px;
    height: 20px;
    margin-bottom: 5px;
  }
}

.grid-content {
  height: 40px;
  text-align: right;
  line-height: 40px;
}

.bg-purple {
  font-size: 14px;
  color: #3f3f3f;
}
</style>
